<template>
	<view class="content">
		<u-navbar :is-back="false" :title="title" title-color="white" :background="background"></u-navbar>
		<view class="item">
			<view class="label">物品名称：</view>
			<view class="input-wrap">
				 <input id="title" :value="info.title" @input="handelInput" class="input" placeholder="请输入物品名称" maxlength="10"/>
			</view>
		</view>
		<view class="item">
			<view class="label">地点名称：</view>
			<view class="input-wrap">
				<input id="place" :value="info.place" @input="handelInput" class="input" placeholder="请输入地点名称" maxlength="10"/>
			</view>
		</view>
		<view class="item">
			<view class="label">发生时间：</view>
			<view class="input-wrap-date">
				<picker mode="date" @change="picker" :value="date" start="2020-09-01" :end="endDate">
				    <view>{{date}}</view>
				</picker>
			</view>
		</view>
		<view class="item">
		    <view class="label">物品描述</view>
		    <view class="input-wrap">
		        <textarea id="desc" :value="info.desc" @input="handelInput"  placeholder="请输入物品描述（300字以内）" maxlength="300"></textarea>
		    </view>
		</view>
		<view class="item">
		    <view class="label">物品图片：</view>
		    <view class="input-wrap">
		        <view class="imgs-wrap">
		            <block v-for="(item, index) in tmpImgs" :key="index">
		                <view class="img-item">
		                    <image mode="aspectFill" :src="item"></image>
		                    <view @click.stop="delPic" :data-index="index" class="img-del"></view>
		                </view>
		            </block>
		            <block v-if="tmpImgs.length < 3">
		                <view class="img-item" @tap="selcetPics">
		                    <image class="sel-pic" mode="aspectFit" src="../../static/upload.svg"></image>
		                </view>
		            </block>
		        </view>
		    </view>
		</view>
		<view class="item">
		    <view class="label">选择类型</view>
		    <!-- <view class="input-wrap">
		        <checkbox-group @change="checkboxChange">
		            <view class="checkbox-item" v-for="(item, index) in concats" :key="item.value">
		                <checkbox :value="item.value"  :disabled="item.disable" />		
		                {{ item.name }} 
		            </view>
		        </checkbox-group>
		    </view> -->
			<view class="page-block" style="margin-top: 20upx;">
				
				<radio-group class="radio-type" @change="typeChange">
					<label class="radio-single">
						<radio  value="1" :checked="type == 1"/>寻物启事        
					</label>
					<label class="radio-single">
						<radio value="0" :checked="type == 0"/>失物招领
					</label>
				</radio-group>
				
			</view>
		</view>
		
		<view class="item">
		    <button @tap="submitNow" class="my-btn submit-btn">提交</button>
		</view>
	</view>
</template>

<script>	
	function getDate(type){
	        const date = new Date();
	        let year = date.getFullYear();
	        // 月份是从0开始计算的, 所以要加一
	        let month = date.getMonth() + 1;
	        let day = date.getDate();
	        if(type === 'start'){
	            /* year = year; */
	        }else if(type == 'end'){
	            year = year;
	        }
	        month = month > 9 ? month: '0' + month;
	        day = day > 9? day: '0' + day;
	        return `${year}-${month}-${day}`;
	    }
	function dateTimeStr(){
		var date = new Date(),
		year = date.getFullYear(),
		month = date.getMonth() + 1,
		day = date.getDate(),
		hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
		minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
		second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
		month >= 1 && month <= 9 ? (month = "0" + month) : "";
		day >= 0 && day <= 9 ? (day = "0" + day) : "";
		var timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
		return timer;
	}
	export default {
		data() {
			return {
				title:"发布",
				background:{
					backgroundImage:'linear-gradient(to top, #ffd655 0%, #fda085 100%)',
					/* background-image: linear-gradient(to top, ffd655#fddb92 0%, #d1fdff 100%); */
				},
				date: getDate({
					format: true
				}),
				pub_date: dateTimeStr({
					format: true
				}),
				startDate:getDate('start'),
				endDate:getDate('end'),
				restype:-1,
				concats: [
				    {
				        name: '寻物启事',
				        value: 'find',
				        checked: 'false'
				    },
				    {
				        name: '失物招领',
				        value: 'lost',
				        checked: 'false'
				    }
				],
				tmpImgs: [],
				tmpImgsindex:0,
				imgurl: [],
				needUploadImg : [],
				uploadIndex : 0,
				info: {
				    title: '',
				    date: '',
				    desc: '',
				    place: '',
				    imgs: [],
				    concat: {},
				    // 联系方式
				    type: ''
				},
				userIsLogin: false
			}
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function (options) {
			var me = this;
			/* me.setData({
			    'info.type': options.type
			}); */
			me.info.type = options.type;
			var userInfo = uni.getStorageSync("globalUser").user;
			me.userInfo = userInfo;
			if (userInfo !=null && userInfo !="" && userInfo !=undefined){
				me.userIsLogin = true;
			
			}else{
				me.userIsLogin=false;

			}
			me.pub_date;
		},

		methods: {
			typeChange(e) {
				var me = this;				
				/* debugger */
				me.type = e.detail.value;
				if (me.type == 1 ){
					me.restype = 1
				}
				if (me.type == 0 ){
					me.restype = 0
				}
			},
			
			submitNow : function(){
				var me = this;
				// 数据验证
				var userInfo = uni.getStorageSync("globalUser").user;
				me.userInfo = userInfo;
				if (!me.userInfo) {
				    return uni.showToast({
				        title: '请登陆',
				        icon: 'none'
				    });
				}
				if (!me.info.title) {
				    return uni.showToast({
				        title: '请输入物品名称',
				        icon: 'none'
				    });
				}
							
				if (!me.info.place) {
				    return uni.showToast({
				        title: '请输入地点',
				        icon: 'none'
				    });
				}
				
				if (!me.info.desc) {
				    return uni.showToast({
				        title: '请对物品进行描述',
				        icon: 'none'
				    });
				}
				if (me.tmpImgs.length === 0) {
				    return uni.showToast({
				        title: '必须有一张图片',
				        icon: 'none'
				    });
				}
				if (me.restype === -1) {
				    return uni.showToast({
				        title: '请选择类别',
				        icon: 'none'
				    });
				}
				if (!me.userInfo.city) {
				    return uni.showToast({
				        title: '请在用户界面添加微信号',
				        icon: 'none'
				    });
				}
				// 上传图片 一次一个多次上传 [ 递归函数 ]
				// 上传完成后整体提交数据
				// 首先整理一下需要上传的图片
				// this.needUploadImg = [{tmpurl : 临时地址, index : 数据索引}]
				/* this.needUploadImg = [];
				for(var i = 0; i < this.tmpImgs.length; i++){
					this.needUploadImg.push({"tmpurl" : this.tmpImgs[i] , "indexID" : i});
				}*/
				this.uploadImg();
				
			},
			uploadImg : function(){
				var me = this;
				if(me.tmpImgsindex<me.tmpImgs.length){
					this.uploadImage_url();
				}else{
					/* console.log("limian");
					var url_in = this.baseUrl + '/mini_program/res/addRes/' + me.userInfo.skey + "?url=" + me.imgurl[0]
					for (var i = 1; i < me.imgurl.length; i++) {
						url_in = url_in + "%2C" + me.imgurl[i]
					} */
					var url_list = JSON.parse(JSON.stringify(me.imgurl))
					var url_list_ = JSON.stringify(me.imgurl)
					//console.log(url_list_);
					console.log(url_list);
					uni.request({
						
						url: this.baseUrl + '/mini_program/res/addRes/' + me.userInfo.skey  ,
						method: 'POST',
						data: {
								  "urls":url_list,
								  "description": me.info.desc,	// 物品描述
								  "location": me.info.place,		// 找到的地址
								  "name": me.info.title,			// 物品名称								  
								  "resType": me.restype,				// 丢失0 找到1 已找到2
								  /* "fineTime": me.pub_date */								  
						},
						
						success: res => {
							if(res.data.code == 20000){
								uni.showToast({title:"提交成功", icon:"none"});
								me.tmpImgs = [];
								// 清空数据
								//signModel.sign(_self.apiServer);
								// 防止数据缓存
								me.info.desc = ' ';
								me.info.place = ' ';
								me.needUploadImg  = [];
								me.info.title = '';
								me.tmpImgsindex=0;
								//me.getNewsList();
								uni.switchTab({
									url:'../index/index',
									success: (res) => {
									        	let page = getCurrentPages().pop();
									        	if (page == undefined || page == null) return;
									        	page.onPullDownRefresh();
									        }
								})
							}else{
								uni.showToast({title:res.data.data, icon:"none"});
							}
						},
						fail: (res) => {
							
						},
						complete: () => {
							
						}
					});
				}
			},	
			uploadImage_url(){
				var me=this;
				var uploader = uni.uploadFile({
					url      : me.baseUrl + '/mini_program/file/upload',
					filePath : me.tmpImgs[me.tmpImgsindex] ,
					name     : 'file',
					header: {
						"Content-Type": "multipart/form-data",
						"token":this.token
					},
					success: (uploadFileRes) => {
						/* debugger */
						uploadFileRes = JSON.parse(uploadFileRes.data);
						/* var index = me.needUploadImg[me.uploadIndex].indexID;
						me.tmpImgs[index] = me.baseimgUrl + uploadFileRes.data[0].url; */
						console.log("服务器传回的地址：");
						console.log(uploadFileRes.data[0].url);
						me.imgurl[me.tmpImgsindex] = uploadFileRes.data[0].url;
						console.log("存到发布接口的数组：");
						console.log(me.imgurl);
						/* console.log(me.imgurl); */
						me.tmpImgsindex ++;
						// 递归上传
						if(me.tmpImgsindex < me.tmpImgs.length){
							me.uploadImage_url();
						}else{
							me.uploadImg();
						}
					},
					fail: () => {
						uni.showToast({title:"上传图片失败,请重试!fail", icon:"none"});
					}
				})
			},
			
			
			/***************************************************************************/
			setData:function(obj){  
			    let that = this;  
			    let keys = [];  
			    let val,data;  
			    Object.keys(obj).forEach(function(key){  
			         keys = key.split('.');  
			         val = obj[key];  
			         data = that.$data;  
			         keys.forEach(function(key2,index){  
			             if(index+1 == keys.length){  
			                 that.$set(data,key2,val);  
			             }else{  
			                 if(!data[key2]){  
			                    that.$set(data,key2,{});  
			                 }  
			             }  
			             data = data[key2];  
			         })  
			    });  
			},
			
			picker: function(e) {
				var me = this;
				me.date = e.detail.value;
				
			},
			handelInput(e) {
				var me = this;
			    const id = e.currentTarget.id;
			    const value = e.detail.value;
			    const obj = {};
			    obj['info.' + id] = value;
			    me.setData(obj);
			},
			delPic(e) {
			    const index = e.currentTarget.dataset.index;
			    const list = [...this.tmpImgs];
			    list.splice(index, 1);
			    this.setData({
			        tmpImgs: list
			    });
			},
			selcetPics() {
				var me = this;
			    console.log(3 - me.tmpImgs.length);			
			    if (me.tmpImgs.length < 3) {
			        uni.chooseImage({
			            count: 3 - me.tmpImgs.length,
			            success: (res) => {
			                //console.log(res);			
			                if (res.tempFilePaths.length > 0) {
			                    me.setData({
			                        tmpImgs: [...me.tmpImgs, ...res.tempFilePaths]
			                    });
			                }
							console.log("本地图片地址");
							console.log(me.tmpImgs);
			            }
			        });
					
			    }
			}
		}
		
	}
</script>

<style>
	.page {
	    background-color: #fff;
	    padding-bottom: 40rpx;
	}
	
	.item {
	    margin: 40rpx;
	    font-size: 28rpx;
	}
	
	.item .label {
	    font-weight: 600;
	    font-size: 28rpx;
	    color: #000;
	    width: 100%;
	    text-align: left;
	    margin-bottom: 14rpx;
	}
	.item .input-wrap-date {
	    height: 100%;
	    box-shadow: 3rpx 3rpx 6rpx rgba(0, 0, 0, 0.1);
	    padding: 10rpx;
		font-size:40rpx;
		text-align:center
		
	}
	
	.item .input-wrap {
	    height: 100%;
	    box-shadow: 3rpx 3rpx 6rpx rgba(0, 0, 0, 0.1);
	    padding: 10rpx;
	}
	
	.input-wrap input {
	    height: 50rpx;
	    color: #000;
	    font-size: 28rpx;
	    padding: 0 28rpx;
	}
	
	.input-wrap textarea {
	    color: #000;
	    font-size: 28rpx;
	    padding: 12rpx 28rpx;
	    height: 150rpx;
	    line-height: 35rpx;
	}
	
	.item .picker {
	    height: 50rpx;
	    line-height: 50rpx;
	    display: flex;
	    justify-content: space-evenly;
	    align-items: center;
	}
	.item checkbox-group {
	    display: flex;
	    justify-content: space-around;
	    flex-wrap: nowrap;
	}
	button.submit-btn {
	    background-color: #fdb92c;
	    border: none;
	    box-shadow: 4rpx 4rpx 5rpx rgba(253, 185, 44, 0.3);
	}
	.imgs-wrap {
	    box-sizing: border-box;
	    padding: 20rpx;
	    display: flex;
	    align-items: center;
	    justify-content: space-between;
	    height: 200rpx;
	}
	
	.img-item {
	    box-sizing: content-box;
	    position: relative;
	    width: 160rpx;
	    height: 160rpx;
	    text-align: center;
	}
	
	.img-item .img-del {
	    position: absolute;
	    right: -15rpx;
	    top: -15rpx;
	    width: 38rpx;
	    height: 38rpx;
	    background-repeat: no-repeat;
	    background-position: center center;
	    background-size: 95% 95%;
	    background-image: url('');
	}
	
	.img-item image {
	    width: 100%;
	    height: 100%;
	}
	
	image.sel-pic {
	    margin-top: 50%;
	    width: 50%;
	    height: 50%;
	    transform: translateY(-50%);
	}
</style>